<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/user' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/task' }">工作台</el-breadcrumb-item>
      <el-breadcrumb-item>任务信息</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row :gutter="20" style="margin-bottom: 20px">
        <el-col :span="9">
          <!-- 3.定义搜索框 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getTaskList">
            <el-button slot="append" icon="el-icon-search" @click="getTaskList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="14">
          <!-- 定义添加按钮-->
          <el-button type="primary" @click="addTaskVisible = true;addTaskBtn()" style="float: right">添加任务
          </el-button>
        </el-col>
      </el-row>
      <el-tabs type="border-card" @tab-click="handleClick">
        <el-tab-pane label="我发布的">
          <el-table :data="taskList" border stripe>
            <el-table-column type="index" label="序号" width="100"></el-table-column>
            <el-table-column prop="taskName" label="任务名称" width="120"></el-table-column>
            <el-table-column prop="releaseName" label="发布人" width="150"></el-table-column>
            <el-table-column prop="empName" label="执行人" width="120"></el-table-column>
            <el-table-column prop="depName" label="执行部门" width="120"></el-table-column>
            <el-table-column prop="taskStatus" label="任务状态"
                             :formatter="taskStatusFormater"></el-table-column>
            <el-table-column prop="createTime" label="发布时间" :formatter="dateFormat" width="120"></el-table-column>
            <el-table-column prop="updateTime" label="更新时间" :formatter="dateFormat" width="120"></el-table-column>
            <el-table-column prop="endTime" label="完成时间" :formatter="dateFormat" width="120"></el-table-column>
            <el-table-column prop="deadlineTime" label="截止时间" :formatter="dateFormat" width="120"></el-table-column>
            <el-table-column label="操作" width="250px" fixed="right">
              <template slot-scope="scope">
                <el-button-group>
                  <el-button type="success" icon="el-icon-view" size="small" @click="toViewTask(scope.row)">查看
                  </el-button>
                  <el-button type="primary" icon="el-icon-edit" size="small" @click="updateTaskBtn(scope.row)">编辑
                  </el-button>
                  <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteTask(scope.row)">删除
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
          <!--分页-->
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                         :current-page="queryInfo.pageNum" :page-sizes="[5, 10, 20, 40]" :page-size="queryInfo.pageSize"
                         layout="total, sizes, prev, pager, next, jumper" :total="total">
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="我执行的">
          <el-table :data="performTaskList" border stripe>
            <el-table-column type="index" label="序号" width="100"></el-table-column>
            <el-table-column prop="taskName" label="任务名称" width="120"></el-table-column>
            <el-table-column prop="releaseName" label="发布人" width="150"></el-table-column>
            <el-table-column prop="empName" label="执行人" width="120"></el-table-column>
            <el-table-column prop="depName" label="执行部门" width="120"></el-table-column>
            <el-table-column prop="taskStatus" label="任务状态"
                             :formatter="taskStatusFormater"></el-table-column>
            <el-table-column prop="createTime" label="发布时间" :formatter="dateFormat" width="120"></el-table-column>
            <el-table-column prop="updateTime" label="更新时间" :formatter="dateFormat" width="120"></el-table-column>
            <el-table-column prop="endTime" label="完成时间" :formatter="dateFormat" width="120"></el-table-column>
            <el-table-column prop="deadlineTime" label="截止时间" :formatter="dateFormat" width="120"></el-table-column>
            <el-table-column label="操作" width="200px" fixed="right">
              <template slot-scope="scope">
                <el-button type="success" icon="el-icon-view" size="small" @click="toViewTask(scope.row)">查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination @size-change="handleSizeChange1" @current-change="handleCurrentChange1"
                         :current-page="queryInfo1.pageNum" :page-sizes="[5, 10, 20, 40]"
                         :page-size="queryInfo1.pageSize"
                         layout="total, sizes, prev, pager, next, jumper" :total="total1">
          </el-pagination>
        </el-tab-pane>
      </el-tabs>

    </el-card>

    <el-dialog title="查看任务详情" :visible.sync="toViewTaskDialogVisible" width="50%" center>
      <!-- 定义用户提交表单数据-->
      <el-form :model="viewTask" label-width="100px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="viewTask.taskName" disabled></el-input>
        </el-form-item>
        <el-form-item label="发布人" prop="releaseName">
          <el-input v-model="viewTask.releaseName" disabled></el-input>
        </el-form-item>
        <el-form-item label="任务状态" prop="phone">
          <el-tag>{{ viewTask.taskStatus }}</el-tag>
        </el-form-item>
        <el-form-item label="任务文件">
          <div v-if="fileList.length !== 0">
            <div v-for="item in fileList">
              <a :href="item.taskFile" target="_blank" :download="item.taskId">
                <el-button type="primary" icon="el-icon-download" size="mini">下载</el-button>
              </a>
            </div>
          </div>
          <div v-else>当前任务无任务文件</div>
        </el-form-item>
        <el-form-item label="任务描述" prop="taskDescribe">
          <quill-editor ref="myQuillEditor" v-model="viewTask.taskDescribe" disabled></quill-editor>
        </el-form-item>
      </el-form>
      <span slot="footer" class="task-footer">
        <el-button type="primary" @click="toViewTaskDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>


    <el-dialog title="添加任务" :visible.sync="addTaskVisible" width="50%" @close="closeTask" center>
      <el-form :model="addTask" ref="addTaskRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="addTask.taskName"></el-input>
        </el-form-item>
        <el-form-item label="任务发布人" prop="releaseName">
          <el-input v-model="addTask.releaseName" disabled></el-input>
        </el-form-item>
        <el-form-item label="执行部门Id">
          <el-cascader v-model="selectedKeys" :props="props" :options="parentDepartmentList" clearable
                       @change="parentItemCatChange" @focus="getDepList"></el-cascader>
        </el-form-item>
        <el-form-item label="执行人Id" prop="empId">
          <el-select v-model="addTask.empId" placeholder="请选择" @focus="getEmpList" @change="change">
            <el-option v-for="item in empList" :key="item.id" :label="item.empName"
                       :value="item.empId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="createTime">
          <el-date-picker v-model="addTask.createTime" type="datetime" format="yyyy年MM月dd日HH时mm分"
                          placeholder="选择截止时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="截止时间" prop="endTime">
          <el-date-picker v-model="addTask.deadlineTime" type="datetime" format="yyyy年MM月dd日HH时mm分"
                          placeholder="选择截止时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="任务描述" prop="taskDescribe">
          <quill-editor ref="myQuillEditor" v-model="addTask.taskDescribe"></quill-editor>
        </el-form-item>
        <el-form-item label="任务文件">
          <el-upload class="upload-demo" :action="uploadUrl" :on-success="handleSuccess"
                     :on-remove="handleRemove" list-type="text">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="task-footer">
        <el-button @click="addTaskVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNewTask()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 定义修改页面 当对话框关闭时,将表格数据重置-->
    <el-dialog title="修改任务" :visible.sync="updateTaskVisible" width="50%" @close="closeUpdateTask" center>
      <!-- 定义用户提交表单数据-->
      <el-form :model="updateTaskModel" ref="updateTaskRef" label-width="100px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="updateTaskModel.taskName" disabled></el-input>
        </el-form-item>
        <el-form-item label="任务执行人" prop="empId">
          <el-input v-model="updateTaskModel.empId" disabled></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="createTime">
          <el-date-picker v-model="updateTaskModel.createTime" type="datetime" format="yyyy年MM月dd日HH时mm分">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="截止时间" prop="endTime">
          <el-date-picker v-model="updateTaskModel.deadlineTime" type="datetime" format="yyyy年MM月dd日HH时mm分">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="任务状态" prop="updateTime">
          <el-select v-model="updateTaskModel.taskStatus" placeholder="请选择">
            <el-option v-for="item in taskStatus" :key="item.index" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务描述" prop="taskDescribe">
          <quill-editor v-model="updateTaskModel.taskDescribe"></quill-editor>
        </el-form-item>
      </el-form>
      <span slot="footer" class="task-footer">
          <el-button @click="updateTaskVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateTask">确 定</el-button>
        </span>
    </el-dialog>

  </div>
</template>

<script>
import moment from "moment";

export default {
  data() {
    return {
      selectedKeys: [],
      parentDepartmentList: [],
      uploadUrl: 'http://localhost:8093/task/uploadTaskFile',
      props: {
        // 定义子节点菜单展开方式
        expandTrigger: 'hover',
        value: 'depId', // 选中数据的value值
        label: 'depName', // 选中数据展现名称
        children: 'children', // 自选项数据
        checkStrictly: true
      },
      taskStatus: [
        {value: 0, label: "进行中"},
        {value: 1, label: "已完成"},
        {value: 2, label: "延期"},
      ],
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 5,
        empId: ''
      },
      queryInfo1: {
        query: '',
        pageNum: 1,
        pageSize: 5,
        empId: ''
      },
      total1: 0,
      taskList: [],
      performTaskList: [],
      empList: [],
      depList: [],
      empName: '',
      total: 0,
      addTaskVisible: false,
      updateTaskVisible: false,
      toViewTaskDialogVisible: false,
      updateTaskModel: [],
      addTask: {
        taskName: '',
        releaseId: '',
        releaseName: '',
        empId: '',
        depId: '',
        createTime: '',
        endTime: '',
        taskStatus: '',
        //任务描述
        taskDescrebe: '',
        // 文件列表
        fileList: []
      },
      fileList: [],
      viewTask: {}
    }
  },
  created() {
    this.queryInfo.empId = this.$cookies.get("empId")
    this.queryInfo1.empId = this.$cookies.get("empId")
    this.getTaskList()
  },
  methods: {
    // 选择标签
    handleClick(tab, event) {
      if (tab.index == 1) {
        this.getPerformTask()
      }
    },
    async getTaskList() {
      const {data: res} = await this.$http.get("task/getTaskList", {
        params: this.queryInfo
      }).catch(
        function (e) {
          alert(e)
        })
      if (res.status !== 200) return this.$message.error("获取任务列表失败")
      this.taskList = res.data.rows
      this.total = res.data.total
    },

    async getPerformTask() {
      const {data: res} = await this.$http.get('/task/getPerformList', {
        params: this.queryInfo1
      }).catch(e => alert(e))
      if (res.status !== 200) return this.$message.error("获取任务列表失败")
      this.performTaskList = res.data.rows
      this.total1 = res.data.total
    },

    handleSizeChange(pageSize) {
      this.queryInfo.pageSize = pageSize
      this.getTaskList()
    },
    handleCurrentChange(pageNum) {
      this.queryInfo.pageNum = pageNum
      this.getTaskList()
    },

    handleSizeChange1(pageSize) {
      this.queryInfo1.pageSize = pageSize
      this.getPerformTask()
    },
    handleCurrentChange1(pageNum) {
      this.queryInfo1.pageNum = pageNum
      this.getPerformTask()
    },

    selectCookie() {
      this.addTask.releaseName = this.$cookies.get('username')
    },

    closeTask() {
      // 重置表格数据
      this.$refs.addTaskRef.resetFields()
    },

    handleSuccess(response, file) {
      if (response.status !== 200) return this.$message.error('文件上传失败')
      file.name = response.data.fileName
      // 获取虚拟路径
      this.addTask.fileList.push(response.data.urlPath)
    },
    // 移除文件
    async handleRemove(file, fileList) {
      console.log(file)
      const urlPath = file.response.data.urlPath
      const dateStr = file.response.data.dateStr
      const index = this.addTask.fileList.findIndex(x => x === urlPath)
      this.addTask.fileList.splice(index, 1)
      const {data: result} = await this.$http.delete('/task/deleteTaskFile', {
        params: {urlPath: urlPath, dateStr: dateStr}
      })
      if (result.status !== 200) return this.$message.error('删除图片失败')
      this.$message.success('删除图片成功')
    },

    async addTaskBtn() {
      this.addTask.releaseName = this.$cookies.get('username')
      this.addTask.releaseId = this.$cookies.get('empId')
    },
    async addNewTask() {
      const res = await this.$http.post("task/addTask", this.addTask).catch(
        function (e) {
          if (e.response.status === 500) {
            alert("服务器故障")
          } else if (e.response.status === 404) {
            alert("页面不存在")
          } else {
            alert("出错")
          }
        })
      if (res.status !== 200) return this.$message.error("添加任务失败")
      this.$message.success("新建任务成功")
      this.addTaskVisible = false
      await this.getTaskList()
      this.addTask = {}
    },

    //获取部门列表
    async getDepList() {
      const {data: res} = await this.$http.get("/task/getDepList/2").catch(error => alert(error))
      if (res.status !== 200) return this.$message.error("获取部门列表失败!!")
      this.$message.success("获取部门信息成功")
      this.parentDepartmentList = res.data
    },
    parentItemCatChange() {
      this.addTask.depId = this.selectedKeys[this.selectedKeys.length - 1]
    },

    //获取部门的员工信息
    async getEmpList() {
      if (!this.addTask.depId) {
        return this.$message.error("请先选择部门")
      }
      const {data: res} = await this.$http.get(`/task/getEmpList/${this.addTask.depId}`).catch(error => alert(error))
      if (res.status !== 200) return this.$message.error("获取部门员工失败")
      if (res.data === null) {
        return this.$message.error("当前部门尚无员工")
      }
      this.empList = res.data
      this.$message.success("获取当前部门员工信息成功")
    },
    change() {
    },

    async updateTaskBtn(row) {
      this.updateTaskModel = row
      this.updateTaskVisible = true
    },

    closeUpdateTask() {
      // 重置表格数据
      this.$refs.updateTaskRef.resetFields()
    },

    async updateTask() {
      const {data: res} = await this.$http.put("/task/updateTask", this.updateTaskModel).catch(
        function (e) {
          alert(e.response.status)
        })
      if (res.status !== 200) return this.$message.error("更新失败")
      this.$message.success("更新成功")
      this.updateTaskVisible = false
      await this.getTaskList()
    },

    async deleteTask(task) {
      const result = await this.$confirm('此操作将永久删除 ' + task.taskName + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)

      //如果确认  confirm  如果取消 cancel
      if (result !== 'confirm') {
        return this.$message.info("删除取消")
      }
      const {data: res} = await this.$http.delete(`/task/deleteTask/${task.id}`).catch(function (e) {
        alert(e)
      })
      if (res.status !== 200) return this.$message.error("删除失败")
      this.$message.success("删除成功")
      await this.getTaskList()
    },

    async toViewTask(row) {
      function status(taskStatus) {
        switch (taskStatus) {
          case 0:
            return "进行中"
          case 1:
            return "已完成"
          case 2:
            return "延期"
        }
      }

      const {data: result} = await this.$http.get(`/task/getTaskInfo/${row.id}`).catch(e => alert(e))
      this.viewTask = result.data
      this.viewTask.taskStatus = status(this.viewTask.taskStatus)
      const {data: res} = await this.$http.get(`task/getTaskFile/${row.id}`).catch(e => alert(e))
      if (res.status !== 200) return this.$message.error("获取任务信息失败")
      this.fileList = res.data
      this.toViewTaskDialogVisible = true
    },

    //用于时间格式化
    dateFormat: function (row, column) {
      const date = row[column.property];
      if (date === null) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD HH:ss");
    },

    taskStatusFormater(row) {
      switch (row.taskStatus) {
        case 0:
          return <el-tag type="primary">进行中</el-tag>
        case 1:
          return <el-tag type="success">已完成</el-tag>
        case 2:
          return <el-tag type="danger">延期</el-tag>
      }
    }


  }
}
</script>

<style scoped>

</style>
